import { Component, OnInit, ViewChild } from '@angular/core';
import { TurboperHistoryService } from '../../../service/turboper-history.service';
import { TurboperHistory } from '../../../entity/turboper-history.model';
import { OperCategorysService } from '../../../service/oper-categorys.service';
import { TurboperCategory } from '../../../entity/turboper-category';
import { OverhaulTableComponent } from '../farm-overhaul/overhaul-table/overhaul-table.component';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';
import { ApplicationService } from '../../../service/application.service';
import { TurbStatusService } from '../../../service/turbstatus.service';
import { DataSourceService } from '../../../service/data-source/data-source.service';
import { InterceptorService } from '../../../service/interceptor/interceptor-service';
import { DatePipe } from '@angular/common';
import { TurbStatus } from '../../../entity/turbstatus.model';
import { Device } from '../../../entity/device.model';

@Component({
  selector: 'app-listed-query',
  templateUrl: './listed-query.component.html',
  styleUrls: ['./listed-query.component.css']
})
export class ListedQueryComponent implements OnInit {
  /**
   * 查询挂牌结束时间
   * 
   * @type {Date}
   * @memberof ListedQueryComponent
   */
  endTime: Date = new Date();
  /**
   * 查询挂牌开始时间
   * 
   * @type {Date}
   * @memberof ListedQueryComponent
   */
  startTime: Date = new Date(this.endTime.getFullYear(), this.endTime.getMonth(), this.endTime.getDate());
  stateEndTime: Date = new Date();
  stateStartTime: Date = new Date(this.stateEndTime.getFullYear(), this.stateEndTime.getMonth(), this.stateEndTime.getDate());

  /**
   * 风机选择定时器
   * 
   * @type {*}
   * @memberof ListedQueryComponent
   */
  timer: any;
  /**
   * 设备id数组
   * 
   * @type {number[]}
   * @memberof ListedQueryComponent
   */
  deviceIds: number[];
  /**
   *设备数据集合
   *
   * @type {Device[]}
   * @memberof ListedQueryComponent
   */
  devices: Device[];
  /**
   * 历史挂牌记录
   * 
   * @type {TurboperHistory[]}
   * @memberof ListedQueryComponent
   */
  turboperHistorys: TurboperHistory[] = [];
  turboperCategorys: SelectTurboperCategory[];
  turbStatuses: SelectTurboperCategory[];
  selectedMultipleOption: string[] = [];
  selectedMultipleOption2: string[] = [];
  selectTurbCategoryIds: number[] = [];
  selectTurbStatusIds: number[] = [];
  stateCodeDatas: StateCodeData[] = [];
  stateDatas: StateCodeData[] = [];
  public deviceCategories: DeviceCategoryEnum[] = [DeviceCategoryEnum.inverter, DeviceCategoryEnum.turbine];
  /**
   *限制设备选择数量
   *
   * @type {number}
   * @memberof ListedQueryComponent
   */
  deviceCountLimit: number;
  ratio = 1;
  /**
   *当前模块下标
   *
   * @type {number}
   * @memberof ListedQueryComponent
   */
  active = 0;
  /**
   *分页中，每页显示的条数
   *
   * @type {number}
   * @memberof ListedQueryComponent
   */
  pageSize: number = 15;
  /**
   *日期格式化
   *
   * @type {*}
   * @memberof ListedQueryComponent
   */
  en:any;
  constructor(
    private turbHistorySer: TurboperHistoryService,
    private operCategorysSer: OperCategorysService,
    private application: ApplicationService,
    private turbStatusService: TurbStatusService,
    private dataSource: DataSourceService,
    private datePipe: DatePipe,
    private http: InterceptorService,
  ) { }

  ngOnInit() {
    this.en = {
      firstDayOfWeek: 0,
      dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
      dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
      today: '今天',
      clear: '清除'
    };
    if (this.application.currentMenuParams && this.application.currentMenuParams['deviceCountLimit']) {
      this.deviceCountLimit = Number(this.application.currentMenuParams['deviceCountLimit'].paramValue);
    } else {
      this.deviceCountLimit = null;
    }
    if (this.application.currentMenuParams && this.application.currentMenuParams['pageSize']) {
      this.pageSize = Number(this.application.currentMenuParams['pageSize'].paramValue);
    } else {
      this.pageSize = 15;
    }
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['ratio']) {
      this.ratio = Number(this.application.currentApplicationParams['ratio'].paramValue);
    }
    this.turbStatusService.getTurbStatus()
      .then(res => {
        if (res) {
          for(var i=0;i<=10000;i++){console.log(i)}
          const turbStatuses = [];
          res.forEach(data => {
            turbStatuses.push({
              label: data.statusName,
              value: data.statusId,
              code: data.statusKey,
              keyValue: data.statusValue
            });
          });
          this.turbStatuses = turbStatuses;
          this.selectedMultipleOption2 = this.turbStatuses.map(o => o.value);
        }
      });
    this.operCategorysSer.getOperCategorysList()
      .then(res => {
        if (res) {

          const turboperCategorys = [];
          res.forEach(data => {
            turboperCategorys.push({
              label: data.operCategoryName,
              value: data.operCategoryId
            });
          });

          this.turboperCategorys = turboperCategorys;
          this.selectedMultipleOption = this.turboperCategorys.map(o => o.value);
        }

      })
      .catch(err => {
        console.log(err);
      });
    if (this.deviceIds && this.deviceIds.length) {
      this.initData();
    }
  }
  initData() {


    this.selectTurbCategoryIds = this.selectedMultipleOption.map(o => Number(o));
    this.turbHistorySer.getHisOperListByTimeAndId(this.startTime, this.endTime, this.deviceIds, this.selectTurbCategoryIds)
      .then(res => {
        if (res) {
          this.turboperHistorys = [...res];
        }
      })
      .catch(err => {
        console.log(err);
      });
  }
  initDataTurbStatus() {
    if (this.selectedMultipleOption2 && this.selectedMultipleOption2.length) {
      this.selectTurbStatusIds = this.selectedMultipleOption2.map(o => Number(o));
    } else {
      this.selectTurbStatusIds = this.turbStatuses.map(o => Number(o.value));
    }
    const turbStatuses = [];

    this.selectTurbStatusIds.forEach(o => {//
      const index = this.turbStatuses.findIndex(data => Number(data.value) === o);

      if (index >= 0) {
        turbStatuses.push(this.turbStatuses[index]);
      }
    });
    this.dataSource = new DataSourceService(this.http, this.datePipe);
    if (this.devices) {
      this.stateCodeDatas = [];
      const stateCodeDatas: StateCodeData[] = [],
        codes = [],
        turbineStatuCode = this.application.tagDict['TurbineStatus'];
      this.devices.forEach((device, index) => {
        const code = this.dataSource.buildTagCode([device.farmCode, device.deviceCode], turbineStatuCode);
        codes.push(code);
        stateCodeDatas.push({
          farmName: device.farmName,
          deviceName: device.deviceName,
          //stateName: turbStatuse.label,
          code: code,
        });

      });
      this.stateCodeDatas = [...stateCodeDatas];
      /* this.http.get("../../../../assets/a.json")
        .toPromise()
        .then(r => {
          let res = r.json();

        }) */
      this.dataSource.history
        .getHistories(codes, this.stateStartTime, this.stateEndTime)
        .then(res => {
          /* const arr = [1, 2, 3, 4, 5];
          codes.forEach((code, index) => {
            res.push({
              code: code,
              time: new Date(Math.random() * 10000000000),
              value: 1
            });
            res.push({
              code: code,
              time: new Date(Math.random() * 10000000000),
              value: 2
            });
            res.push({
              code: code,
              time: new Date(Math.random() * 100000000),
              value: 3
            });

          }); */
          const stateDatas = [];
          this.stateCodeDatas.forEach(data => {

            const deviceStateDatas = res.filter(o => o.code === data.code);
            deviceStateDatas.sort((a, b) => {
              return new Date(a.time).getTime() - new Date(b.time).getTime();
            });
            let deviceState: StateCodeData,
              deviceStates: StateCodeData[] = [];
            deviceStateDatas.forEach(deviceStateData => {
              const index = turbStatuses.findIndex(o => Number(o.keyValue) == deviceStateData.value);
              if (index >= 0) {
                if (deviceState) {
                  const hours = (new Date(deviceStateData.time).getTime() - new Date(deviceState.startTime).getTime()) / 3600000;
                  deviceState.endTime = deviceStateData.time;
                  deviceState.hours = Math.round(hours * 100) / 100;
                  deviceStates.push(deviceState);
                }
                deviceState = {
                  farmName: data.farmName,
                  deviceName: data.deviceName,
                  stateName: turbStatuses[index].label,
                  code: data.code,
                  startTime: deviceStateData.time,
                  endTime: null,
                  hours: 0,
                };
              }
            });
            if (deviceState) {
              deviceStates.push(deviceState);
            }
            stateDatas.push(...deviceStates);

            //const codeDatas = res.filter(data => data.code === o.stateCode);
            /* o.startTime = new Date(2018, 7, 2);
            o.endTime = new Date(); */
          });
          this.stateDatas = [...stateDatas];
        });

    }
    //const codes = this.stateCodeDatas.map(o => o.stateCode);

  }
  public onClickHeader(n: number) {
    this.active = n;
    if (this.active) {
      this.initDataTurbStatus();
    }
  }
  onSelectedDevicesChange(ev) {
    clearTimeout(this.timer);
    this.devices = [...ev];
    this.deviceIds = [];
    this.deviceIds.push(...ev.map(o => o.deviceId));
    //this.alarmList.turbineIds = this.deviceIds;
    this.timer = setTimeout(() => {
      if (!this.turboperHistorys || !this.turboperHistorys.length) {
        this.initData();
      }
      //this.initAlarmList();
    }, 2000);
  }



}
interface SelectTurboperCategory {
  label: string;
  value: string;
  code?: string;
  keyValue?: string
}
interface StateCodeData {
  farmName: string;
  deviceName: string;
  stateName?: string;
  code: string;
  startTime?: Date;
  endTime?: Date;
  hours?: number;
}



// WEBPACK FOOTER //
// ./src/app/module/data-analysis/listed-query/listed-query.component.ts